package com.xxadmin.common.web;


import com.xxadmin.common.exception.ParamIllageException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 基础 Controller
 *
 * @author:chenming
 * @date:2018/5/7
 */
@Slf4j
public class BaseController extends HttpBaseController{

    /**
     * 校验参数
     *
     * @author chenming
     * @date 2017-09-26
     */
    public <T> void validate(T t) {
        ValidatorFactory vFactory = Validation.buildDefaultValidatorFactory();
        javax.validation.Validator validator = vFactory.getValidator();
        Set<ConstraintViolation<T>> set = validator.validate(t);
        if (set.size() > 0) {
            StringBuilder validateError = new StringBuilder();

            for (ConstraintViolation<T> val : set) {
                validateError.append(val.getMessage()).append(",");
            }

            // 非法参数异常
            throw new ParamIllageException("000901",
                    validateError.substring(0,validateError.length() -1));
        }
    }
}
